var g_progressPercent = 0;

var g_arrMyPlacemarks = new Array();
var g_arrStyles = new Array();

var g_arrHouses = new Array();
g_arrHouses[-2] = "brown";
g_arrHouses[-1] = "red";
g_arrHouses[0] = "yellow";
g_arrHouses[1] = "green";
g_arrHouses[2] = "purple";

var g_ge = null;
var g_gex = null;

var g_folder = null;

var g_infoDiv = null;

var criteria = {
	search: '',
	rating: '',
	zip: [],
	city: []
}

google.load("earth", "1");

$(function()
{
	// events for mini search form above results
	$("#properties input#search").keyup(function(){
		setTimeout(SearchTextChanged, 1000);
	});
	$("#properties select#rating").change(function(e){
		criteria.rating = $(e.target).val();
		RefreshData();
	});		   
});

function ShowProgress()
{
	//this works for shit
	$( "#progressbar" ).progressbar("option", "value", g_progressPercent);
}

// This is the real initialization, since we aren't really good to go until the google earth plugin is ready
function init()
{
	google.earth.createInstance("map_canvas", function (instance){
		g_ge = instance;
		g_ge.getWindow().setVisibility(true);
		g_ge.getNavigationControl().setVisibility(g_ge.VISIBILITY_SHOW);
		g_ge.getOptions().setScaleLegendVisibility(g_ge.VISIBILITY_SHOW)
		g_ge.getOptions().setTerrainExaggeration(2.2);
		// add some layers
		g_ge.getLayerRoot().enableLayerById(g_ge.LAYER_BORDERS, true);
		g_ge.getLayerRoot().enableLayerById(g_ge.LAYER_ROADS, true);
		g_ge.getLayerRoot().enableLayerById(g_ge.LAYER_TERRAIN, true);
		g_gex = new GEarthExtensions(g_ge);
		
		var highlightIcon = g_ge.createIcon('gray');
		highlightIcon.setHref('http://househunter.planetsnook.com/images/monopoly-house-gray24.png?');
		
		var highlightStyle  = g_ge.createStyle(''); //create a new style
		highlightStyle.getIconStyle().setIcon(highlightIcon); //apply the icon to the style
		highlightStyle.getIconStyle().setScale(.75);
		highlightStyle.getLabelStyle().setScale(0);
		
		// Creates the styles to be applied to placemarks
		for(var i = -2; i <= 2; i++)
		{
			// Create a style map.
			var styleMap = g_ge.createStyleMap('');

			var normalIcon = g_ge.createIcon(g_arrHouses[i]);
			normalIcon.setHref('http://househunter.planetsnook.com/images/monopoly-house-' + g_arrHouses[i] + '24.png?i=' + i);
			
			var normalStyle = g_ge.createStyle(''); //create a new style
			normalStyle.getIconStyle().setIcon(normalIcon); //apply the icon to the style
			normalStyle.getIconStyle().setScale(.75);
			normalStyle.getLabelStyle().setScale(0);
			
			styleMap.setNormalStyle(normalStyle);
			styleMap.setHighlightStyle(highlightStyle);

			g_arrStyles[i] = styleMap;
		}
		InitializeCheckBoxes();
		RefreshData();
	}, function (errorCode) {
		alert("earth fail: " + errorCode);
	});
	$( "#progressbar" ).progressbar();

}

function SearchTextChanged()
{
	criteria.search = $("input#search").val();
	if (criteria.search.length == 0){
		$.cookie('search', null);
	}
	else
	{
		$.cookie("search", criteria.search, {expires:365});
	}
	RefreshData();	
}

function RefreshData()
{
	$("#modal_overlay").show();
	$("#modal_overlay #message").center();
	$("#map_canvas").hide();
	g_progressPercent = 0;
	$( "#progressbar" )
		.progressbar("option", "value", 0)
		.progressbar( "option", "disabled", true );

	criteria.zip = new Array();
	criteria.city = new Array();
	// begin checkbox code
	$.each(['zip', 'city'], function(idx, filtertype)
	{
		$("input."+ filtertype +"Check:checked").each(function(i, elem)
		{
			criteria[filtertype].push($(elem).val());
		});
	});
	
	$("filter_info").html('');
	if(criteria.zip.length)
		$("#filter_info").html("zips: " + criteria.zip.join(', '));
	if(criteria.city.length)
		$("#filter_info").html(" cities: " + criteria.city.join(', '));
	
	//remove the listed records
	$("#properties div.record").detach();

	$("#modal_overlay #text").html("Requesting Data");

	//get the data
	$.get('lib/SearchQuery.php', {
		QueryID: "properties",
		search: criteria.search,
		rating: criteria.rating,
		zip: criteria.zip.join(','),
		city: criteria.city.join(','),
		OutputType: 'JSON'
	},
	function(data){
		$("#modal_overlay #text").html("Parsing data");
		$("span#sql").html(data.SQL);
		$( "#progressbar" ).progressbar( "option", "disabled", false );
		var count = data.Rows.length;
		var toID = window.setInterval(ShowProgress, 500);
		$.each(data.Rows, function(i, record)
		{
			g_progressPercent = Math.floor((i/count) * 100);
			
			var sOut = '<div class="record ui-widget-content" id="'+ record.id +'">';
    		sOut += '<input id="id" type="hidden" value="'+ record.id +'" />';
    		sOut += '<img id="rating" src="images/monopoly-house-' + g_arrHouses[record.rating] + '24.png" alt=""/>';
			sOut += record.address + ', ' + record.city + ' ' + record.zip + ', ';
			sOut += record.county + ' County, Price: $' + record.price + '</div>';
			$("#properties").append(sOut);
		});
		
		$("#properties div.record").hover(function(e)
		{
			$(e.target).addClass('ui-state-hover');
		},
		function(e){
			$(e.target).removeClass('ui-state-hover');
		}).click(function(e)
		{
			GetPropertyInfo($(e.target).find("input#id").val());
		});
		
		window.clearInterval(toID);
		RenderHouseLayer(data.Rows);
		$( "#progressbar" ).progressbar( "option", "disabled", true );
		$("#map_canvas").show();
		$("#modal_overlay").hide();
	 }, 'json');
	
}

function PlacemarkClick(event)
{
	event.preventDefault();
	setTimeout(function() {
		GetPropertyInfo(event.getTarget().getName());
	}, 0);
}

function RenderHouseLayer(data)
{
	g_gex.dom.clearFeatures();
	g_arrMyPlacemarks = new Array();
	var arrPlacemarks = new Array();
	
	$("#modal_overlay #text").html("Creating Placemarks");
	$( "#progressbar" ).progressbar("option", "value", 0);
	count = data.length;
	var toID = window.setInterval(ShowProgress, 500);
	$.each(data, function(idx, record)
	{
		g_progressPercent = Math.floor((idx/count) * 100);

		var placemark = g_gex.dom.buildPointPlacemark([parseFloat(record.lat), parseFloat(record.lon)],{
			name: record.id,
			style: g_arrStyles[record.rating]
		});
		google.earth.addEventListener(placemark, 'click', PlacemarkClick);
		g_arrMyPlacemarks[record.id] = placemark;
		arrPlacemarks.push(placemark);
	});
	window.clearInterval(toID);
	var la = g_ge.getView().copyAsLookAt(g_ge.ALTITUDE_RELATIVE_TO_GROUND);
	la.setAltitude(6269.889595987072);
	la.setHeading(0);
	la.setTilt(60.32191525083331);
	la.setRange(0.0014558725217884757);
	g_ge.getView().setAbstractView(la);
	g_folder = g_gex.dom.addFolder(arrPlacemarks);
	
	g_gex.util.flyToObject(g_folder);
	//var bounds = g_gex.dom.computeBounds(g_folder);
	// You could also use g_gex.view.setToBoundsView(bounds, { aspectRatio: 1.0 });
}

function SavePropertyAuxInfo()
{
	var rec = {
		mls_id: $("#details span#mls_id", g_infoDiv).text(),
		comments: $("textarea#comments", g_infoDiv).val(),
		rating:$("select#rating", g_infoDiv).val()
	};
	$.get("lib/savePropertyAux.php", rec);
	var id = $('#details input#id', g_infoDiv).val();
	// code goes here for updating icon on map and data list
	g_arrMyPlacemarks[id].setStyleSelector(g_arrStyles[rec.rating])
	$('#properties .record[id="' + id + '"] img').attr('src', 'http://househunter.planetsnook.com/images/monopoly-house-' + g_arrHouses[rec.rating] + '24.png');

}

function GetPropertyInfo(id)
{
	$.getJSON("lib/getPropInfo.php", {id:id}, function(data)
	{
		//New! Street view tab
		//old - var panoramaOptions = {
		//old - 	position: 			g_arrMyPlacemarks[id].getPosition(),
		//old - 	enableCloseButton: 	false,
		//old - 	visible: true
		//old - };
		//old - var panorama = new google.maps.StreetViewPanorama($("#pano")[0], panoramaOptions);
		//old - map.setStreetView(panorama);
		
		$("#property_tabs").bind('tabsshow', function(event, ui) {
			if (ui.panel.id == "streetviewtab") {
				//old - google.maps.event.trigger(panorama, 'resize');
			}
		});

		var placemark = g_arrMyPlacemarks[id];
		var placemark_name = placemark.getName();
		var balloon = g_ge.createHtmlDivBalloon('');
		balloon.setFeature(placemark);
		balloon.setMinWidth(475);
		balloon.setMaxWidth(600);
		balloon.setMaxHeight(550);
		balloon.setMinHeight(500);
		g_infoDiv = $("#PropertyWindow").clone()[0];
		deserialize($(g_infoDiv), data);
		// this bit adds the Images (3) to the tab text
		var imgCnt = $("#images_panel img", g_infoDiv).length;
		if(imgCnt > 0)
		{
			$("#property_tabs", g_infoDiv).tabs("enable", 1);
			$($("#property_tabs ul li span", g_infoDiv)[1]).html("Images (" + imgCnt + ")");
		}
		else
		{
			$("#property_tabs", g_infoDiv).tabs("disable", 1);
			$($("#property_tabs ul li span", g_infoDiv)[1]).html("Images");
		}
		
		$("#zoomTo", g_infoDiv).click(function()
		{
			g_gex.util.flyToObject(g_arrMyPlacemarks[id]);
			//old - map.panTo(g_arrMyPlacemarks[id].getPosition());
			//old - map.setZoom(18);
			
		});

		$("#property_tabs", g_infoDiv).tabs();
		$("select#rating", g_infoDiv).change(SavePropertyAuxInfo);
		$("textarea#comments", g_infoDiv).blur(SavePropertyAuxInfo);
		balloon.setContentDiv(g_infoDiv);
		g_ge.setBalloon(balloon);

		
	}); // END $.getJSON("getPropInfo.php", {id:id}, function(data)
}

function deserialize(joContainer, data){
	$.each(data, function(key, value){
		//debugger;
		var thing = joContainer.find("#"+key);
		if (thing.length)
		{
			switch(thing[0].nodeName.toLowerCase())
			{
				case 'div':
				case 'span':
				case 'p':
					thing.html(value);
					break;
				case 'a':
					thing.attr('href', value);
					break;
				case 'input':
				case 'textarea':
				case 'select':
					if(key == 'rating' && value == null) value = 0;
					thing.val(value);
					break;
				default:
					break;
			}
		}
		//console.log(key + '=' + value);
	});
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
